<?php
include("../../../../common.php");
$state = $_GET['state'];
$code = $_GET['code'];
if (!$code or !$state) pe_404('参数错误，请重试');
$arr = explode('@', $_g_state);
$state = $arr[0];
switch($state) {
	//网页扫码登录回调
	case 'wx_pc_login':
		$appid = $cache_setting['login_wx_appid'];
		$secret = $cache_setting['login_wx_appsecret'];
	break;
	//公众号登录回调
	case 'wx_gzh_login':
		$_GET['sessid'] = $arr[1];
		$appid = $cache_setting['wechat_appid'];
		$secret = $cache_setting['wechat_appsecret'];
	break;
	default:
		pe_404('参数错误，请重试');
	break;
}

//获取access_token和openid
$json = pe_curl_get("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code");
$json = json_decode($json, true);
if (!$json['openid']) pe_404('获取access_token异常：'.json_encode($json).'，请重试');
$openid	= $json['openid'];
$access_token = $json['access_token'];

//获取unionid
$json = pe_curl_get("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}");
$json = json_decode($json, true);	
if (!$json['unionid']) pe_404('获取unionid异常：'.json_encode($json).'，请重试');	

$login3 = pe_get_session('login3');
$login3 = is_array($login3) ? $login3 : array();
$login3['user_name'] = $json['nickname'];
$login3['user_logo'] = $json['headimgurl'];
$login3['user_wx_openid'] = $json['openid'];
$login3['user_wx_unionid'] = $json['unionid'];
$login3['from'] = 'wx';
pe_set_session('login3', $login3);
switch($state) {
	//网页扫码登录回调
	case 'wx_pc_login':
		pe_goto("{$pe['host']}user.php?mod=do&act=login3");
	break;
	//公众号登录回调
	case 'wx_gzh_login':
		pe_goto(pe_url('/page/user/do_login3', 'app'));
		//pe_back_uniapp('/page/user/do_login3');
	break;
}